package com.my.structuraltype.proxy.cglib;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class BookFacadeCglib implements MethodInterceptor {

	private Object target;  
	
	// 和下面的方法其实一样
	@SuppressWarnings("unchecked")
	public <T> T getProxy(Class<T> cls) {
		return (T) Enhancer.create(cls, this);
	}
	  
    /** 
     * 创建代理对象 
     *  
     * @param target 
     * @return 
     */  
    public Object getInstance(Object target) {  
        this.target = target;  
        Enhancer enhancer = new Enhancer();  
        enhancer.setSuperclass(this.target.getClass());
        // 回调方法  
        enhancer.setCallback(this);  
        // 创建代理对象  
        return enhancer.create();  
    }  
  
    @Override  
    // 回调方法  
    // obj,即产生的代理类,继承了目标类
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {  
        System.out.println("事务开始");  
        proxy.invokeSuper(obj, args);
        method.invoke(target, args);// same as above
        
        System.out.println(obj.getClass());
//        ((BookFacadeImpl)obj).addBook("");// cause endless loop
        
        
        
        
        System.out.println("事务结束");  
        return null;  
  
  
    }  


}
